<template>
    <div class="ticket-table-wrapper">
        <param-selector :model.sync="searchParams" :type="type" @search="fetchTicketList(1)"></param-selector>

        <Row align="middle" justify="space-between" style="margin:16px 0 8px 0;padding-left:14px;" type="flex">
            <Col span="8">
                <Button @click="goToTicketCreate" type="primary">新建工单</Button>
                <!-- <Button @click="handleExport" type="primary">数据导出</Button> -->
            </Col>

            <Col span="16" style="text-align:right;padding-right:10px;">
                <!-- <span style="margin-right:10px">待处理工单共 <strong class="color-red"> ??? </strong> 笔</span> -->
                <Button :type="currentOrderBtn==='created_at'?'primary':'default'" @click="setOrder('created_at')">创建日期
                    <Icon :color="orders.created_at==='DESC' ? '':'#666'" type="arrow-down-c"></Icon>
                    <Icon :color="orders.created_at==='DESC' ? '#666':''" type="arrow-up-c"></Icon>
                </Button>

                <Button :type="currentOrderBtn==='appointment_time'?'primary':'default'" @click="setOrder('appointment_time')">预约上门时间
                    <Icon :color="orders.appointment_time==='DESC' ? '':'#666'" type="arrow-down-c"></Icon>
                    <Icon :color="orders.appointment_time==='DESC' ? '#666':''" type="arrow-up-c"></Icon>
                </Button>
            </Col>
        </Row>

        <Row align="middle" class="list-table-head" type="flex">
            <Col span="4">房源信息</Col>
            <template v-if="type === '1'">
                <Col span="4">房间</Col>
                <Col span="4">下单设备</Col>
            </template>

            <Col span="4" v-if="type === '2'">故障设备</Col>
            <Col span="4" v-if="type === '4'">重装设备</Col>
            <Col span="4" v-if="type === '3'">拆卸设备</Col>
            <Col span="4" v-if="type !== '1'">工单紧急度</Col>

            <Col span="4">联系信息</Col>
            <Col span="4">状态</Col>
            <Col span="4">操作</Col>
        </Row>

        <div class="list-table-body">
            <div :key="item.id" class="list-table-row" v-for="item in ticketList">
                <Row align="middle" class="ticket-title" type="flex">
                    <Col span="24">
                        <span>&nbsp;&nbsp;工单编号：{{item.ticket_sn}}</span>
                        <span class="spilt">|</span>
                        <span>创建时间：{{item.created_at | date('YYYY-MM-DD HH:mm')}}</span>
                        <span class="spilt">|</span>
                        <span v-if="type==='1'">预约上门时间：{{ item.appointment_time | date('YYYY-MM-DD') }} {{item.appointment_period | appointmentPeriod}}</span>
                        <span v-else>预约上门时间：{{ item.appointment_time | date('YYYY-MM-DD HH:mm') }}</span>                    </Col>
                </Row>

                <Row align="middle" class="ticket-content" type="flex">
                    <!-- 房源信息 -->
                    <Col span="4">
                        <div style="text-align: left;">
                            <div class="ticket-info-item">房源编号：{{item.home_info && item.home_info.home_name}}</div>
                            <div class="ticket-info-item">地址：{{concatAddress(item.home_info)}}</div>
                        </div>
                    </Col>

                    <template v-if="type === '1'">
                        <!-- 房间 -->
                        <Col span="4">
                            <span :key="index" v-for="(r,index) in 3" v-if="item.ticket_devices[index]">
                                <span v-show="index > 0">,</span>
                                {{item.ticket_devices[index].room_name}}
                            </span>
                            <span v-if="item.ticket_devices[3]">
                                ... (
                                <a
                                    @click="goToTicketDetail(item)"
                                    class="color-green"
                                    href="javascript:;"
                                >共{{item.ticket_devices.length}}个房间</a>)
                            </span>
                        </Col>
                        <!-- 下单设备 -->
                        <!-- <Col span="4">{{item.service_target | ticketDeviceType}}</Col> -->
                    </template>

                    <!-- 故障/重装/拆卸设备 -->
                    <Col span="4">{{genDevices(item)}}</Col>

                    <template v-if="type !== '1'">
                        <!-- 工单紧急度 -->
                        <Col span="4">
                            <span style="font-weight:bold" v-if="item.respond_hour">{{item.respond_hour}} 小时上门</span>
                            <span v-else>-</span>
                        </Col>
                    </template>

                    <!-- 联系信息 -->
                    <Col span="4" style="text-align: left;">
                        <div class="ticket-info-item">下单人: {{item.subscribe.name}} ({{item.subscribe.phone}})</div>
                        <div
                            class="ticket-info-item"
                            v-if="item.contact_person"
                        >现场联系人: {{item.contact_person.name}} ({{item.contact_person.phone}})</div>
                        <Poptip title="工单备注" trigger="hover" v-if="item.subscribe.note" width="300">
                            <div class="color-green">工单备注</div>
                            <div class="pop-tip-content" slot="content">{{ item.subscribe.note }}</div>
                        </Poptip>
                    </Col>

                    <!-- 状态 -->
                    <Col span="4">
                        <div class="ticket-info-item">
                            <span>{{item.state | ticketState(type)}}</span>
                        </div>
                        <div class="ticket-info-item" v-if="item.implementer">
                            <span>{{item.implementer.name}} ({{item.implementer.telephone}})</span>
                        </div>
                    </Col>

                    <!-- 操作 -->
                    <Col class="operate-btns" span="4">
                        <Button
                            @click="copyTicketInfo(item)"
                            class="copy-btn"
                            size="small"
                            type="ghost"
                            v-if="getIfBtnShouldExist(item,'复制')"
                        >复制</Button>
                        <Button @click="goToTicketDetail(item)" size="small" type="ghost" v-if="getIfBtnShouldExist(item,'详情')">详情</Button>
                        <Button @click="acceptTicket(item, false)" size="small" type="ghost" v-if="getIfBtnShouldExist(item,'驳回')">驳回</Button>
                        <Button @click="acceptTicket(item, true)" size="small" type="ghost" v-if="getIfBtnShouldExist(item,'通过')">通过</Button>
                        <Button @click="cancelTicket(item)" size="small" type="ghost" v-if="getIfBtnShouldExist(item,'取消')">取消</Button>
                    </Col>
                </Row>
            </div>
            <Spin fix size="large" v-show="isLoading"></Spin>
            <div class="no-data-tip" v-show="!pagination.count">暂无数据</div>
        </div>

        <!--分页-->
        <Page
            :current.sync="pagination.currentPage"
            :page-size="pagination.size"
            :total="pagination.count"
            @on-change="fetchTicketList"
            show-elevator
            show-total
            style="text-align:center;padding:20px 0;"
        ></Page>
        <!--分页end-->
        <select-engineer
            :show.sync="selectEngineerVisible"
            :tickets.sync="currentTickets"
            @refresh="fetchTicketList(pagination.currentPage)"
        ></select-engineer>

        <change-engineer-modal
            :show.sync="changeEngineerVisible"
            :ticket.sync="currentTicket"
            @refresh="fetchTicketList(pagination.currentPage)"
        ></change-engineer-modal>

        <mobileSolutionModal
            :show.sync="mobileSolutionVisible"
            :ticket.sync="currentTicket"
            @refresh="fetchTicketList(pagination.currentPage)"
        ></mobileSolutionModal>

        <acceptance-modal
            :result="acceptanceResult"
            :show.sync="acceptanceVisible"
            :ticket.sync="currentTicket"
            @refresh="fetchTicketList(pagination.currentPage)"
        ></acceptance-modal>

        <cancel-modal :show.sync="cancelVisible" :ticket.sync="currentTicket" @refresh="fetchTicketList(pagination.currentPage)"></cancel-modal>
    </div>
</template>

<script>
import util from '@/libs/util'
import { confirmBackModal } from '../util'
import { mapActions, mapGetters } from 'vuex'
import { http, api } from '@/libs/http'
import filters from '@/filters'
import { ServiceType, TicketOperateBtns } from '@/libs/const'
import Clipboard from 'clipboard/dist/clipboard'
import EventBus from '@/libs/event-bus'

import paramSelector from '../components/param-selector'
import selectEngineer from './modal/selectEngineer'
import changeEngineerModal from './modal/changeEngineerModal'
import mobileSolutionModal from './modal/mobileSolutionModal'
import acceptanceModal from './modal/acceptanceModal'
import cancelModal from './modal/cancelModal'
export default {
  //  service_type: INTEGER, // 工单类型 1: 安装 2：维修 3：拆回 4：重装
  props: ['type'],

  components: {
    paramSelector,
    selectEngineer,
    changeEngineerModal,
    mobileSolutionModal,
    acceptanceModal,
    cancelModal
  },

  data () {
    return {
      isLoading: true,
      clipboard: null,
      ticketList: [],
      checkAll: false,
      pagination: {
        count: 0,
        size: 10,
        currentPage: 1
      },
      orders: {
        created_at: 'DESC',
        appointment_time: 'DESC'
      },
      currentOrderBtn: '',

      searchParams: {},

      currentTicket: null,
      currentTickets: [],

      selectEngineerVisible: false,
      changeEngineerVisible: false,
      mobileSolutionVisible: false,
      acceptanceVisible: false,
      acceptanceResult: true,
      cancelVisible: false
    }
  },

  mounted () {
    this.fetchTicketList()
    EventBus.$on('REFRESH_TICKET_LIST', this.fetchTicketList)
  },

  computed: {
    ...mapGetters(['isCustomerService'])
  },

  methods: {
    ...mapActions(['addTicketTab']),
    concatAddress: util.concatAddress,
    goToTicketCreate () {
      this.$router.push({
        name: 'ticket-create',
        query: {
          service_type: this.type
        }
      })
    },

    goToTicketDetail (ticket) {
      this.addTicketTab({
        type: 'detail',
        ticket: ticket
      })
      this.$router.push({
        path: `/ticket/detail/${ticket.id}`
      })
    },

    goToTicketEdit (ticket) {
      this.addTicketTab({
        type: 'edit',
        ticket: ticket
      })
      this.$router.push({
        path: `/ticket/edit/${ticket.id}`
      })
    },

    generateParams (limit, page) {
      const data = this.searchParams
      if (limit && page) {
        data.limit = limit
        data.offset = (page - 1) * limit
      }
      return data
    },

    // 设置排序条件
    setOrder (orderType) {
      this.currentOrderBtn = orderType

      // 切换排序箭头
      if (this.orders[orderType] === 'DESC') {
        this.orders[orderType] = 'ASC'
      } else {
        this.orders[orderType] = 'DESC'
      }
      this.fetchTicketList()
    },

    /**
         * 获取工单列表
         * @param page 页码
         * @param order 排序方式
         */
    async fetchTicketList (page = 1) {
      if (page === 1) this.pagination.currentPage = 1
      const params = this.generateParams(this.pagination.size, page)

      if (this.currentOrderBtn) {
        // 得到类似 order: ["created_at","DESC"]
        params.order = [this.currentOrderBtn, this.orders[this.currentOrderBtn]]
      } else {
        delete params.order
      }

      // 数组参数转为json
      Object.keys(params).forEach(key => {
        const value = params[key]
        if (Array.isArray(value)) params[key] = JSON.stringify(value)
      })

      util.log('===fetchTicketList params===', params)

      this.isLoading = true
      try {
        const res = await http.fetch(this, api.ticket_list, [this.type], params)
        if (res) {
          this.ticketList = res.rows
          this.checkAll = false
          this.pagination.count = res.count
        }
      } catch (error) {
        util.log('===fetchTicketList ERROR===', error)
      } finally {
        this.isLoading = false
      }
    },

    /**
         * 统计设备数量
         * @param {Array} devices ticket_devices 房间设备信息
         * return {string} 设备数量字符串
         */
    genDevices (ticket) {
      return filters.ticketDeviceModel(ticket)
    },

    getIfBtnShouldExist (ticket, btnName) {
      const btnArray = TicketOperateBtns[this.type][ticket.state] || []
      if (btnName === '打回客服' && this.isCustomerService) return false
      return btnArray.includes(btnName)
    },

    copyTicketInfo (ticket) {
      this.clipboard && this.clipboard.destroy()

      this.clipboard = new Clipboard('.copy-btn', {
        text: trigger => {
          return this.generateTicketText(ticket).trim()
        }
      })

      this.clipboard.on('success', e => this.$Message.success('工单信息已复制'))
    },

    generateTicketText (item) {
      // 此处不要有缩进 为了对齐
      let result = `
工单类型: ${ServiceType[item.service_type] || '未知'}工单
工单状态: ${filters.ticketState(item.state, this.type)}
工单编号: ${item.ticket_sn}
下单设备: ${this.genDevices(item)}
创建时间: ${filters.date(item.created_at, 'YYYY-MM-DD HH:mm')}
房源编号: ${item.home_info.home_name}
房源地址: ${util.concatAddress(item.home_info)}
下单人: ${item.subscribe.name} ${item.subscribe.phone}
工单备注: ${item.subscribe.note || '无'}`

      if (item.implementer && item.implementer.name) {
        result += `\n分配师傅: ${item.implementer.name} ${item.implementer.telephone}`
      }

      if (item.contact_person && item.contact_person.name) {
        result += `\n现场联系人: ${item.contact_person.name} ${item.contact_person.phone}`
      }

      // 不同的工单类型添加不同的复制内容
      switch (this.type) {
        case '1':
          result += `\n预约上门时间: ${filters.date(item.appointment_time, 'YYYY-MM-DD')} ${filters.appointmentPeriod(item.appointment_period)}`
          result += `\n房间: 共${item.ticket_devices ? item.ticket_devices.length : 0}个房间`
          break

        default:
          result += `\n预约上门时间: ${filters.date(item.appointment_time, 'YYYY-MM-DD HH:mm')}`
          result += `\n工单紧急度: ${item.respond_hour ? item.respond_hour + '小时上门' : '-'}`
      }
      return result
    },

    // 受理工单弹窗提示
    receiveTicket (ticket) {
      const modalConfig = {
        title: '受理工单',
        content: util.escapeHtml(`将受理工单: 商户:${ticket.client.name};工单编号:${ticket.ticket_sn},<br>
                受理工单后请及时联系客户。`),
        onOk: () => this.confirmReceiveTicket(ticket)
      }
      this.$Modal.confirm(modalConfig)
    },

    // 受理工单发送请求
    async confirmReceiveTicket (ticket) {
      const res = await http.fetch(this, api.ticket_service_ack, [ticket.id])
      if (res) {
        this.$Notice.info({
          title: '工单受理成功',
          desc: '您已受理工单，请及时联系客户。'
        })
        this.fetchTicketList()
      }
    },

    selectEngineer (ticket) {
      this.currentTickets = [ticket]
      this.selectEngineerVisible = true
    },

    changeEngineer (ticket) {
      this.currentTicket = ticket
      this.changeEngineerVisible = true
    },

    showMobileSolution (ticket) {
      this.currentTicket = ticket
      this.mobileSolutionVisible = true
    },

    backToAdmin (ticket) {
      confirmBackModal(this, ticket, this.confirmBackToAdmin)
    },
    confirmBackToAdmin (ticket_id, description) {
      http.request(this, api.ticket_reject, [ticket_id], { ticket_id, description }, (res, err) => {
        this.$Modal.remove()
        if (err) {
          this.$Message.error(err.data.err_msg)
          return
        }
        this.$Message.success('打回成功')
        this.fetchTicketList()
      })
    },

    handleCheckAll () {
      this.ticketList.forEach(item => {
        item.checked = this.checkAll
      })
    },
    handleBatchSelectEngineer () {
      let ticketCitys = []
      const selecedTicket = this.ticketList.filter(ticket => {
        if (ticket.checked && !this.disabledTicket(ticket)) {
          return ticketCitys.push(ticket.home_info.city)
        }
      })

      ticketCitys = [...new Set(ticketCitys)]
      if (ticketCitys.length > 1) {
        this.$Modal.confirm({
          title: '分配师傅提示',
          content: util.escapeHtml(`您选中的工单不属于同个城市:[${ticketCitys.join(',')}] ，确定分配给同个师傅？`),
          onOk: () => {
            this.currentTickets = selecedTicket
            this.selectEngineerVisible = true
          }
        })
        return
      }

      if (selecedTicket.length === 0) {
        this.$Message.info('请选择要批量分配的工单')
      } else {
        this.currentTickets = selecedTicket
        this.selectEngineerVisible = true
      }
    },

    // 验收 / 驳回
    acceptTicket (ticket, value) {
      this.currentTicket = ticket
      this.acceptanceResult = value
      this.acceptanceVisible = true
    },

    cancelTicket (ticket) {
      this.currentTicket = ticket
      this.cancelVisible = true
    },

    // 待验收、已验收和已关闭的工单，不显示复选框。
    disabledTicket (ticket) {
      const stateText = filters.ticketState(ticket.state, this.type)
      const arr = ['待验收', '已验收', '已关闭']
      return arr.includes(stateText)
    }
  },

  beforeDestroy () {
    this.clipboard && this.clipboard.destroy()
  }
}
</script>

<style lang="less">
.ticket-table-wrapper {
    background-color: #fff;
    .pop-tip-content {
        padding: 10px;
        white-space: normal;
        max-height: 300px;
        overflow: auto;
        .ivu-tag {
            min-width: 66px;
        }
    }
    .color-red {
        color: #fd0000;
    }
    .color-green {
        color: #05bac5;
        cursor: pointer;
    }
    .text-active {
        color: #2d8cf0;
    }
    .list-table-head {
        text-align: center;
        padding: 10px 0 10px 10px;
        font-weight: bold;
        background-color: #efeff1;
        font-size: 16px;
        border: 1px solid #bbbec4;
        .ivu-col {
            padding: 2px 10px;
            &:last-child {
                padding: 0px;
            }
        }
    }
    .list-table-body {
        min-height: 100px;
        position: relative;
        .ivu-col {
            padding: 10px 10px;
            &:last-child {
                padding: 10px 0px;
            }
        }
    }
    .no-data-tip {
        background-color: #fefefe;
        text-align: center;
        font-size: 14px;
        padding: 50px;
    }
    .list-table-row {
        margin-top: 10px;
        border: 1px solid #bbbec4;
        background-color: #fff;
        border-radius: 4px;
        &:first-child {
            margin-top: 10px;
        }
        &:hover {
            box-shadow: 1px 1px 2px 3px rgba(0, 0, 0, 0.1);
            background-color: #fffbe6;
        }
        .ticket-title {
            background-color: #efeff1;
            border-bottom: 1px solid #bbbec4;
            padding-left: 6px;
            font-weight: bold;
            .spilt {
                margin: 0 20px;
            }
        }
        .ticket-content {
            text-align: center;
            padding: 0 0 0 10px;
            // min-height: 144px;
        }
        .ticket-info-item {
            margin: 8px 0;
        }
        .operate-btns {
            text-align: left;
            button {
                margin: 8px 4px;
                min-width: 64px;
            }
        }
    }
}
</style>
